package com.amox.uitest.kit;

import java.io.File;
import java.io.IOException;
import java.util.logging.*;

/**
 * @description: LogUtilFactory
 */
public class LogFactory {
	// Name of the global Log
    public static final String LOG_NAME = "Global";

//     This file path must exist. If it does not exist, an error will be reported and it will not be created automatically
//    public static final String LOG_FOLDER = "/data/local/tmp/MpcLog";
    public static final String LOG_FOLDER = "/mnt/sdcard/UITestLog";
    
 // Normal date format
    public static final String DATE_PATTERN_FULL = "yyyy-MM-dd HH:mm:ss";
    // An unsigned date format used to record time stamps
    public static final String DATE_PATTERN_NOMARK = "yyyyMMddHHmmss";

    // log file path
    private static String log_filepath;

    // Static variable globleLog
    private static Logger globalLog;

    static {
    	File logdir = new File(LOG_FOLDER);
    	if (!logdir.exists()) {
    		System.out.println("The log folder does not exist and is being created. The directory is:"+logdir.getAbsolutePath());
			if(logdir.mkdirs()) {
				System.out.println("The log folder is created successfully. The directory is as follows:"+logdir.getAbsolutePath());
			}else{
				System.out.println("Failed to create the log folder. Procedure");
			};
		}
    	
        // The full path to the log file is initialized when the class is loaded. The file name is JDKLog_+ timestamp +.log
//    	log_filepath = LOG_FOLDER + File.separator + "JDKLog_" + LogUtil.getCurrentDateStr(LogUtil.DATE_PATTERN_NOMARK)
//                + ".log";
    	log_filepath = LOG_FOLDER + File.separator + "UITest" +".log";
        // globleLog is initialized directly when the class is loaded
        globalLog = initGlobalLog();
    }

    /**
     * Initialize the global Logger
     * 
     * @return
     */
    public static Logger initGlobalLog() {

        // Obtaining Log
        Logger log = Logger.getLogger(LOG_NAME);

        // Set the global log Level. ALL Level is the lowest level and is used to enable all log records.
        log.setLevel(Level.ALL);

        // Adding a Console handler
        addConsoleHandler(log, Level.INFO);

        // Add a file output handler
        addFileHandler(log, Level.INFO, log_filepath);

        // Set handlers not to apply to the parent class, so that the output is not repeated on the console
        log.setUseParentHandlers(false);

        return log;
    }
    
    /**
     * Add a console handler to the log
     * 
     * @param log
     *            To add handler's log
     * @param level
     *            Output level of the console
     */
    public static void addConsoleHandler(Logger log, Level level) {
//        // handler for the console output
//        ConsoleHandler consoleHandler = new ConsoleHandler();
//        // Set the level of console output (output to console at the level of FileHandler if ConsoleHandler is higher than or equal to log level, output to console at the level of FileHandler if it is lower than Log level)
//        consoleHandler.setLevel(level);
//        consoleHandler.setFormatter(new Formatter() {
//			
//			@Override
//			public String format(LogRecord record) {
//				// TODO Auto-generated method stub
//				return record.getMessage() +  " [ " + getCurrentDateStr(DATE_PATTERN_FULL) + " - Level:"
//                + record.getLevel().getName().substring(0, 1) + " ]-" + "[" + record.getSourceClassName()
//                + " -> " + record.getSourceMethodName() + "()] " + "\n";
//			}
//		});
//
//        // Add the handler to the console
//        log.addHandler(consoleHandler);
    }

    /**
     * Add a file output Handler for log
     * 
     * @param log
     *            To add the log of the file output handler
     * @param level
     *            log output level
     * @param filePath
     *            Specifies the full path of the file
     */
    public static void addFileHandler(Logger log, Level level, String filePath) {
        FileHandler fileHandler = null;

        try {
            fileHandler = new FileHandler(filePath, true);
            // Set the level of the output file (if the level of FileHandler is higher than or equal to the log level, the output is based on the level of FileHandler; if the level is lower, the output is based on the Log level).
            fileHandler.setLevel(level);

            fileHandler.setFormatter(new Formatter() {
                @Override
                public String format(LogRecord record) {

                    //                    // Set the file output format
//                    return record.getMessage() +  "[ " + CommonUtils.getCurrentDateStr(DATE_PATTERN_FULL) + " - Level:"
//                            + record.getLevel().getName().substring(0, 1) + " ]-" + "[" + record.getSourceClassName()
//                            + " -> " + record.getSourceMethodName() + "()] " + "\n";
                    // Set the file output format
                    return record.getMessage() + "\n";
                }
            });

        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // Add the output file handler
        log.addHandler(fileHandler);
    }

    public static Logger getGlobalLog() {
        return globalLog;
    }
}
